import { DataTypes } from 'sequelize';
import { sequelize } from '../config/database.js';

const ServiceIntegration = sequelize.define('ServiceIntegration', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  service_name: {
    type: DataTypes.STRING(100),
    allowNull: false,
    comment: '服务名称，如：system_k'
  },
  display_name: {
    type: DataTypes.STRING(100),
    allowNull: false,
    comment: '显示名称，如：知识库管理系统'
  },
  base_url: {
    type: DataTypes.STRING(500),
    allowNull: true,
    comment: '基础URL地址'
  },
  api_key: {
    type: DataTypes.STRING(500),
    allowNull: true,
    comment: 'API密钥'
  },
  api_config: {
    type: DataTypes.JSON,
    allowNull: true,
    comment: 'API接口配置JSON',
    get() {
      const value = this.getDataValue('api_config');
      return value ? (typeof value === 'string' ? JSON.parse(value) : value) : {};
    },
    set(value) {
      this.setDataValue('api_config', value ? JSON.stringify(value) : null);
    }
  },
  last_test_time: {
    type: DataTypes.DATE,
    allowNull: true,
    comment: '最后测试时间'
  },
  last_test_result: {
    type: DataTypes.JSON,
    allowNull: true,
    comment: '最后测试结果',
    get() {
      const value = this.getDataValue('last_test_result');
      return value ? (typeof value === 'string' ? JSON.parse(value) : value) : null;
    },
    set(value) {
      this.setDataValue('last_test_result', value ? JSON.stringify(value) : null);
    }
  },

  created_at: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  },
  updated_at: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  }
}, {
  tableName: 'service_integrations',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at',
  indexes: [
    {
      name: 'idx_service_integrations_service_name', // 添加固定名称
      fields: ['service_name'],
      unique: true
    }
  ]
});

// 实例方法
ServiceIntegration.prototype.toJSON = function() {
  const values = { ...this.get() };
  return values;
};

// 类方法
ServiceIntegration.getByServiceName = function(serviceName) {
  return this.findOne({
    where: { service_name: serviceName }
  });
};

ServiceIntegration.getAllServices = function() {
  return this.findAll({
    order: [['service_name', 'ASC']]
  });
};

// 初始化默认配置
ServiceIntegration.initDefaultConfig = async function() {
  const defaultConfigs = [
    {
      service_name: 'system_k',
      display_name: '知识库管理系统',
      base_url: '',
      api_key: '',
      api_config: {
        getExpertList: {
          path: '/experts',
          method: 'GET',
          description: '获取专家列表，返回专家的外部ID和昵称'
        },
        getQaDetail: {
          path: '/qa/{request_id}',
          method: 'GET',
          description: '获取问答详情，需传入问答的request_id'
        }
      }
    },
    {
      service_name: 'system_a',
      display_name: '用户前端系统',
      api_config: {
        expertDetailPage: {
          urlTemplate: '',
          description: '专家详情页面URL模板，用于生成专家个人页面链接'
        },
        staticImage: {
          urlTemplate: '',
          description: '静态图片URL模板，用于生成图片的完整访问链接'
        }
      }
    }
  ];

  for (const config of defaultConfigs) {
    const existing = await this.findOne({
      where: { service_name: config.service_name }
    });

    if (!existing) {
      await this.create(config);
      console.log(`✅ 创建默认服务配置: ${config.display_name}`);
    }
  }
};

export default ServiceIntegration;
